
require(['loading'], function(loading) {
	//获取url中的id参数
	var params = getUrlParams();
	var first = params.first?params.first:"";
	
	var expressArea = "";
	var page = 0;
	
	history.pushState({},"","");
	pushVHistory();
	window.onpopstate = function(event) {
		if(page<1){
			goBackVHistory();
		}else{
			history.pushState({},"","");
			page = page -1;
			$('#modifyName, #modifyCompany, #modifyPosition, #modifyMobile, #areaLayer').animate({"bottom": "-100%"});;
			$('#list').show();
		}
	};
	
    //应用实例化
    var personalDetail = new Vue({
        el: '#personalDetail',
        data: {
            detail: {},
            roles: [],
            roles2: [],
            provinceData:[],
			cityData: [],
			countyData: [],
            showLoading: false,
			isProv: false,
			isCity: false,
			isCout: false,
            payPasswordUrl:'',
            apiUrl: wxUrl + '/v3.2/tuser/detail',
            modifyUrl: wxUrl + '/v3.2/tuser/modifyDetail',
            areaUrl: wxUrl + '/v3.2/addr/areaList',
            imgUrl: wxUrl + '/v3.2/tuser/upload',
            validCode: true,
            yzmUrl: wxUrl + '/v3.2/login/verifyCode',
            changeUrl: wxUrl + '/v3.2/tuser/modifyMobile',
            yzmitem: {
                params:{
                    token: token,
                    mobile: '',
                    msgType:3
                }
            },
            changeitem: {
                params:{
                    token: token,
                    userToken:userToken,
                    newMobile: '',
                    exp:'',
                    verifyToken:'',
                    verifyCode:''
                }
            },
            item: {
                params:{
                    token: token,
                    userToken: userToken
                }
            },
            modifyItem: {
                params:{
                    token: token,
                    userToken: userToken,
                    areaId: '',
                    company: '',
                    headPic: '',
                    nickName: '',
                    position: '',
                    role: ''
                }
            },
            areaItem: {
				params:{
					token: token,
					userToken: userToken,
					parentAreaId: ''
				}
			},
			imgItem: {
				params:{
					token: token,
					userToken: userToken,
					file: {}
				}
			}
        },
        ready: function() {
            this.getPersonalDetailData();
            bindMobileKeyUp();
            bindYzmClick();
            bindSubmit();
        },
        methods: {
            getPersonalDetailData: function() {
                this.$http.get(this.apiUrl, this.item)
                    .then(function(response) {
                        var result = JSON.parse(response.body);
                        var detailData = result.data.tuser;
                        var rolesData = result.data.role;
                        var rolesData2 = rolesData.splice(1);
                        this.$set('detail', detailData);
                        this.$set('roles', rolesData);
                        this.$set('roles2', rolesData2);
                    },function(response) {
                        //errorCallback
                    });
            },
            clickModify: function (type) {
            	history.pushState({},"","");
            	page = page + 1;
            	$('#list').hide();
            	if(type == 1){
            		$('#modifyName').animate({"bottom": 0}); //姓名
            	} else if(type == 2){
            		$('#modifyCompany').animate({"bottom": 0}); //公司
            	} else if(type == 3){
            		$('#modifyPosition').animate({"bottom": 0}); //职位
            	} else if(type == 4){
            		$("#areaLayer").animate({"bottom": 0});//地区
            		this.getProvince();
            	} else if(type == 5){
            		$('#modifyRole').animate({"bottom": 0}); //角色
            	} else if(type == 6){
            		$('#list').show();
            		$('#modifyMobile').animate({"bottom": 0});  //手机号
            	}
            },
            modifySubmit: function (e, type) {
            	if (type == 1) {
            		var nickName = $('#userName').val();
            		if(nickName == null || nickName == undefined || nickName == "" || nickName.length<2){
            			promptBox('姓名必须大于两个字！');
				        return;
				    }else{
				    	var reg = /^[a-zA-z0-9\u4E00-\u9FA5]*$/;
						if(!reg.test(nickName)){
							promptBox('姓名不能含有特殊字符！');
				        	return;
						}
				    }
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    headPic: this.detail.headPic,
	                    nickName: nickName,
	                    company: this.detail.company,
	                    position: this.detail.position,
	                    areaId: this.detail.areaId,
	                    role: this.detail.role
					};
            	} else if (type == 2) {
            		var company = $('#userCompany').val();
            		if(company == null || company == undefined || company == "" || company.length<2){
            			promptBox('公司名必须大于两个字！');
				        return;
				    }else{
				    	var reg = /^[\(\)\（\）\u4E00-\u9FA5]+$/;
						if(!reg.test(company)){
							promptBox('公司名不能含有特殊字符！');
				        	return;
						}
				    }
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    headPic: this.detail.headPic,
	                    nickName: this.detail.nickName,
	                    company: company,
	                    position: this.detail.position,
	                    areaId: this.detail.areaId,
	                    role: this.detail.role
	                };
            	} else if (type == 3) {
            		var position = $('#userPosition').val();
            		if(position == null || position == undefined || position == "" || position.length<2){
            			promptBox('职位必须大于两个字！');
				        return;
				    }else{
				    	var reg = /^[\(\)\（\）\u4E00-\u9FA5]+$/;
						if(!reg.test(position)){
							promptBox('职位不能含有特殊字符！');
				        	return;
						}
				    }
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    headPic: this.detail.headPic,
	                    nickName: this.detail.nickName,
	                    company: this.detail.company,
	                    position: position,
	                    areaId: this.detail.areaId,
	                    role: this.detail.role
	                };
	            } else if (type == 4) {
	            	this.isProv = false;
					this.isCity = false;
					this.isCout = false;
					$("#areaLayer").animate({"bottom": "-100%"});
            		var areaId = $(e.currentTarget).attr('id');
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    headPic: this.detail.headPic,
	                    nickName: this.detail.nickName,
	                    company: this.detail.company,
	                    position: this.detail.position,
	                    areaId: areaId,
	                    role: this.detail.role
	                };
	            } else if (type == 5) {
            		var role = $(e.currentTarget).attr('id');
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    headPic: this.detail.headPic,
	                    nickName: this.detail.nickName,
	                    company: this.detail.company,
	                    position: this.detail.position,
	                    areaId: this.detail.areaId,
	                    role: role
	                };
	            } else if (type == 6) {
	            	
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    headPic: this.detail.headPic,
	                    nickName: this.detail.nickName,
	                    company: this.detail.company,
	                    position: this.detail.position,
	                    areaId: this.detail.areaId,
	                    role: this.detail.role
	                };
	            }
            	this.$http.get(this.modifyUrl, this.modifyItem)
                    .then(function(response) {
                        var result = JSON.parse(response.body);
                        if(result.code == 0){
                        	if(result.data.complete){
                        		var complete = localStorage.getItem('complete');
								if(complete != 'true'){
									promptBox('已填写完所有信息！');
								}
                        		localStorage.setItem("complete", true);
                        	}
                        	if(result.data.success){
                        		page = page - 1;
                        		this.getPersonalDetailData();
                        		$('#modifyName, #modifyCompany, #modifyPosition, #modifyMobile').animate({"bottom": "-100%"});
                        		$('#list').show();
                        	}else{
                        		promptBox("修改失败，请重试！");
                        	}
                        }
                    },function(response) {
                        //errorCallback
                    });
            },
            getProvince: function(){
				this.areaItem.params.parentAreaId = '';
				this.isProv = true;
				this.isCity = false;
				this.isCout = false;
				$("#areaBox").scrollTop(0);
//				expressArea = "";
				//获取省份
				this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('provinceData', result.data.result);
					},function(response) {
						//errorCallback
					});
			},
			getCity: function(e){
				this.areaItem.params.parentAreaId = $(e.currentTarget).attr('id');
				$('.backCity').attr('id',$(e.currentTarget).attr('id'));
				this.isProv = false;
				this.isCity = true;
				this.isCout = false;
//				expressArea += $(e.currentTarget).text() + " > ";
				$("#areaBox").scrollTop(0);
				//获取城市
				this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('cityData', result.data.result);
					},function(response) {
						//errorCallback
					});
			},
			getCounty: function(e){
				this.areaItem.params.parentAreaId = $(e.currentTarget).attr('id');
				this.isProv = false;
				this.isCity = false;
				this.isCout = true;
//				expressArea += $(e.currentTarget).text() + " > ";
				$("#areaBox").scrollTop(0);
				//获取县区
				this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('countyData', result.data.result);
					},function(response) {
						//errorCallback
					});
			},
            checkMaxInput: function (e, maxLen) {
            	var obj = $(e.currentTarget).val();
            	var maxlen = $(e.currentTarget).next();
			    if(obj == null || obj == undefined){
			        return;
			    }
			    if(maxLen == null || maxLen == undefined || maxLen == ""){
			        maxLen = 20;
			    }
			    var strResult;
			    if(obj.length > maxLen) { //如果输入的字数超过了限制
			    	$(e.currentTarget).val(obj.substring(0, maxLen)); //就去掉多余的字
			        strResult = maxLen - obj.length;
			    } else {
			        strResult = maxLen - obj.length;
			    }
			    if(strResult<0){
			    	strResult=0;
			    }
			    maxlen.text(strResult);
			    // if(maxlen.text() == 0){
			    //     maxlen.text(0);
			    // }else{
			    //     maxlen.text(strResult);
			    // }
			},
//			modifyMobile: function(){
//				window.location.href = self_base_path + "/userCenter/personalData/changeMobile.html";
//			},
			noSelect: function(){
				promptBox("暂不可选择其他角色!");
			},
			 getyzm: function() {
                if(!checkPhone()){
                    return;
                }
                var phone = $("#tel").val();
                var code=$(".msgs");
                personalDetail.yzmitem.params.mobile=phone;
                var time=60;
                if (this.validCode) {
                    this.validCode=false;
                    code.addClass("msgs1");
                    this.$http.get(this.yzmUrl, this.yzmitem)
                    .then(function(response) {
                        var result = JSON.parse(response.body);
                        if(result.data!=null){
                            var success = result.data.success;
                            console.log(success)
                            if(success){
                                var t=setInterval(function  () {
                                    time--;
                                    code.html(time+"s后重发");
                                    if (time==0) {
                                        clearInterval(t);
                                        code.html("重发验证码")
                                        code.css("color","#FF9500");
                                        personalDetail.validCode=true;
                                        code.removeClass("msgs1");
                                    }
                                },1000)
                                this.changeitem.params.exp = result.data.exp;
                                this.changeitem.params.verifyToken = result.data.verifyToken;
                            }else{
                                this.validCode=true;
                                code.removeClass("msgs1"); 
                            }
                        }else{
                            this.validCode=true;
                            code.removeClass("msgs1"); 
                        }
                    },function(response) {
                        //errorCallback
                    });
                }
            },
            toChangeMobile: function() {
                this.$http.get(this.changeUrl, this.changeitem)
                    .then(function(response) {
                        var result = JSON.parse(response.body);
                        if(result.code != null && result.code == 0){
                            if(result.data!=null){
                                var success = result.data.success;
                                if(success){
                                    promptBox("更改手机号成功");
                                     setTimeout(function(){
                                     	$('#modifyMobile').animate({"bottom": "-100%"});;
                                     },1000)
                                }else{
                                    promptBox("更改手机号失败，请重试");
                                }
                            }
                        }
                        
                    },function(response) {
                        //errorCallback
                    });
            }
        }
    });
    
	$(function(){
		//打开省市区选项
		$("#expressArea").click(function(){
			$("#areaLayer").animate({"bottom": 0});
		});
		//关闭省市区选项
		$("#areaLayer header").click(function(){
			$("#areaLayer").animate({"bottom": "-100%"});
			$('#list').show();
		});
		var ua = navigator.userAgent.toLowerCase();	
		if (/android/.test(ua)) {
		    $('#multi-file').attr( 'capture', 'camera');
		}
	});
	//上传头像
	$('#multi-file').on('click', function(){
		(function () {
		    var	multi_file = document.getElementById('multi-file'),
		        file_list = document.getElementById('file-list'),
		        slice = Array.prototype.slice;
		    var GUID = 0;
		    function guid() { return GUID++; };
		    multi_file.addEventListener('change', function (e) {
		        var files = slice.call(multi_file.files, 0),
		            htmls = ['<tr><th></th></tr>'];
		        files.forEach(function (file, index) {
		            var reader,_guid = guid();
		            if (file.type.toLowerCase().match(/image.*/)) {
		                reader = new FileReader();
		                reader.addEventListener('load', function (e) {
		                    document.getElementById('file-list').innerHTML = '<img src="' + e.target.result + '"/>';
		                });
		                reader.readAsDataURL(file);
		                reader.onload=function(e){
							var formData = new FormData(document.getElementById("uploadAjaxImage"));
							$.ajax({
								url: wxUrl + '/v3.2/tuser/upload',
								type: "POST",
								data: formData,
								contentType:false,
								cache:false,
								processData:false,
								success:function(data){
									if(data.data.success){
										promptBox('上传成功！');
										personalDetail.detail.headPic = data.data.url;
										personalDetail.modifySubmit(this,6);
									} else{
										promptBox('上传失败！');
									}
								},
								error:function(data){
									promptBox('上传文件过大！');
								}
							});
						}
		            };
		        });
		        file_list.innerHTML = htmls.join('');
		    }, false);
		})();
	});
//	$(document).on('input propertychange','textarea', function() {
//		var reg = /^[a-zA-z0-9\u4E00-\u9FA5]*$/;
//		if(reg.test($(this).val())){
//			return true;
//		}else{
//			$(this).val("");
//		}
//	});	
	 function bindMobileKeyUp(){
        $('.content').on('keyup',function(){
            $('.clear').show();
        });
        $('.clear').click(function(){
            $(this).hide();
            $('.content').val('');
        });
    }

    function bindYzmClick(){
        //获取短信验证码
        $(".msgs").click(function() {
            personalDetail.getyzm();
        })
    }

    function checkPhone(){
        var phone = $("#tel").val();
        if(phone == "") {
            promptBox("手机号码不能为空");
        } else {
            var re = /^[1][34587]\d{9}$/; //手机号码验证正则表达式
            if(re.test(phone)) {
                return true;
            } else {
                promptBox("请输入正确的手机号码");
            }
        }
        return false;
    }

    function bindSubmit(){
        $("#submit").click(function() {
            if(checkPhone()){
                var yzm = $("#yz").val();
                if(yzm == ''){
                    promptBox("请输入验证码");
                    return;
                }
                personalDetail.changeitem.params.verifyCode=yzm;
                var phone = $("#tel").val();
                personalDetail.changeitem.params.newMobile=phone;
                personalDetail.detail.mobile = phone;
                personalDetail.toChangeMobile();               
            }
        });
    }
});
